package com.yuanhua.sim.netty.serve.handler;

import com.yuanhua.core.base.entity.LoginReqBean;
import com.yuanhua.core.base.entity.MsgRecBean;
import com.yuanhua.core.base.entity.MsgReqBean;
import com.yuanhua.core.base.entity.MsgResBean;
import com.yuanhua.sim.netty.utils.NettyAttrUtil;
import com.yuanhua.sim.netty.utils.SessionUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * * @description TODO
 * * @author songguoxiang@yunquna.com
 * * @date 2024/03/29 17:15
 */
@Slf4j
public class MsgReqHandler extends SimpleChannelInboundHandler<MsgReqBean> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MsgReqBean msgReqBean) throws Exception {
        NettyAttrUtil.updateReaderTime(channelHandlerContext.channel(), System.currentTimeMillis());
        //2.发送消息请求
        log.info("客户端发送消息：{}", msgReqBean.toString());
        sendMsg(msgReqBean,channelHandlerContext.channel());
    }
    /**
     * 发送消息给指定
     * @param:
     * @param bean 消息类型
     * @param channel 通道
     * @return: void
     * @author songguoxiang
     * @date: 2022/8/1 16:49
     */
    private void sendMsg(MsgReqBean bean, Channel channel){
        Long toUserId =bean.getTouserid();
        Channel c= SessionUtils.getChannel(toUserId);

        if(c==null){
            //人不在线，回调给网关，让其下线
            MsgResBean res=new MsgResBean();
            res.setStatus(1);
            res.setMsg(toUserId +",不在线");
            channel.writeAndFlush(res);
        }else{
            MsgRecBean res=new MsgRecBean();
            res.setFromuserid(bean.getFromuserid());
            res.setMsg(bean.getMsg());
            c.writeAndFlush(res);
        }
    }
}
